/*******************************************************************************
* Copyright (c) 2010, 2018 西安秦晔信息科技有限公司
* Licensed under the Apache License, Version 2.0 (the "License");
*    you may not use this file except in compliance with the License.
*    You may obtain a copy of the License at
*
*       http://www.apache.org/licenses/LICENSE-2.0
*
*    Unless required by applicable law or agreed to in writing, software
*    distributed under the License is distributed on an "AS IS" BASIS,
*    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*    See the License for the specific language governing permissions and
*    limitations under the License.
*******************************************************************************/
package com.qinyeit.webapp.controller.management.members;

import com.alibaba.fastjson.JSONObject;
import com.qinyeit.serviceapp.entity.*;
import com.qinyeit.serviceapp.entity.enums.MemberMakeCardType;
import com.qinyeit.serviceapp.entity.enums.PeriodType;
import com.qinyeit.serviceapp.exception.BusinessRunTimeException;
import com.qinyeit.serviceapp.service.members.MemberCardService;
import com.qinyeit.serviceapp.service.members.MemberCardTypeBranchService;
import com.qinyeit.serviceapp.service.members.MemberCardTypeService;
import com.qinyeit.serviceapp.service.organization.BranchService;
import com.qinyeit.serviceapp.service.organization.DistrictService;
import com.qinyeit.serviceapp.utils.CompuUtils;
import com.qinyeit.serviceapp.utils.SearchUtils;
import com.qinyeit.webapp.controller.management.BaseManagementController;
import com.qinyeit.webapp.utils.CurrentAccountUtils;
import com.qinyeit.webapp.utils.SearchableUtils;
import com.qinyetech.springstage.core.entity.search.Searchable;
import com.qinyetech.springstage.core.lang.QyMap;
import com.qinyetech.springstage.core.utils.JSONUtils;
import com.qinyetech.springstage.core.web.annotation.PageableDefaults;
import com.qinyetech.springstage.core.web.annotation.PermissionInfo;
import com.qinyetech.springstage.core.web.dto.ResponseResult;

import com.qinyeit.serviceapp.service.members.BatchCardRecordService;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

/**
 * ClassName: BatchCardRecordsController <br/>
 * Function: batchCardRecord [批量制卡记录] <br/>
 * date: 2018-12-04 11:14:20 <br/>
 *
 * @author liuwenjin
 * @version  1.0
 * @since JDK 1.8
 */
@RestController
@RequestMapping("/management/members/batchCardRecords")
@PermissionInfo(parentName ="基础信息管理" ,parentOrder = 10,order = 10,code = "management_batchCardRecord:read",name ="批量制卡记录",deleteAble = false)
public class BatchCardRecordsController extends BaseManagementController{

	@Autowired
	private BatchCardRecordService batchCardRecordService;
	@Autowired
	private MemberCardTypeService memberCardTypeService;
	@Autowired
	private MemberCardService memberCardService;
	@Autowired
	private DistrictService districtService;
	@Autowired
	private MemberCardTypeBranchService memberCardTypeBranchService;
	@Autowired
	private BranchService branchService;

	private final String [] keys = {"id","no","cardType.id:cardTypeId","cardType.name:cardTypeName","cardPre","startNo","count","deposit",
            "period","deliverCount","exclude","createAt"};

    @RequiresPermissions("management_batchCardRecord:show")
    @PermissionInfo(code = "management_batchCardRecord:show",name ="查看",deleteAble = false)
    @RequestMapping(method = {RequestMethod.GET, RequestMethod.POST})
    @PageableDefaults(sort = "id=desc")//默认按照id降序
    public ResponseResult<JSONObject> index(Searchable searchable){
        searchable = SearchableUtils.newSearchableWithMerchantFilter(searchable);
        Page<BatchCardRecord> batchCardRecordPage = batchCardRecordService.findAll(searchable);
        QyMap map = QyMap.map("batchCardRecordPage",JSONUtils.include(batchCardRecordPage,new Class[]{PeriodType.class}, keys));
        initFormDate(map);
        return ok("查询成功",map );
    }

    @GetMapping("/create")
    public ResponseResult<QyMap> _new(){
        QyMap map=QyMap.NEW();
        map.setv("batchCardRecord",JSONUtils.include(new BatchCardRecord(), keys));
        initFormDate(map);
        return ok("初始化成功", map);
    }


    @RequiresPermissions("management_batchCardRecord:create")
    @PermissionInfo(code = "management_batchCardRecord:create",name ="新增",deleteAble = false)
    @PostMapping("/create")
    public ResponseResult<String> create(@ModelAttribute @Valid BatchCardRecord batchCardRecord, BindingResult bindingResult){
//        if(batchCardRecordService.exists(buildExists(null, "no", batchCardRecord.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        batchCardRecord.setMerchantGroupId(CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        batchCardRecordService.saveData(batchCardRecord);
//        //批量保存会员卡
        return ok("保存成功");
    }

    @GetMapping("/{id}")
    public ResponseResult<JSONObject> show(@ModelAttribute BatchCardRecord batchCardRecord){
        return ok("查询成功", JSONUtils.include(batchCardRecord, keys));
    }

    @GetMapping("/{id}/update")
    public ResponseResult<QyMap> edit(@ModelAttribute BatchCardRecord batchCardRecord){
        QyMap map=QyMap.NEW();
        map.setv("batchCardRecord",JSONUtils.include(batchCardRecord, keys));
        initFormDate(map);
        return ok("查询成功",map);
    }

    @RequiresPermissions("management_batchCardRecord:update")
    @PermissionInfo(code = "management_batchCardRecord:update",name ="修改",deleteAble = false)
    @PutMapping("/{id}/update")
    public ResponseResult<String> update(@ModelAttribute @Valid BatchCardRecord batchCardRecord,BindingResult bindingResult){
//        if(batchCardRecordService.exists(buildExists(null, "no", batchCardRecord.getNo()))){
//             bindingResult.rejectValue("no","no.error","编号已经存在");
//        }
        if (bindingResult.hasErrors()) {
            return super.validateFail(bindingResult);
        }
        batchCardRecordService.update(batchCardRecord);
        return ok("更新成功", null);
    }

    @RequiresPermissions("management_batchCardRecord:destory")
    @PermissionInfo(code = "management_batchCardRecord:destory",name ="删除",deleteAble = false)
    @DeleteMapping("/{id}")
    public ResponseResult<String> destory(@PathVariable Long id){
        BatchCardRecord record = batchCardRecordService.findById(id);
        if(record.getDeliverCount().intValue()>0){
            return fail("已配送的会员卡不能进行删除");
        }
        //删除批量制卡
        batchCardRecordService.deleteData(id);
        return ok("删除成功", null);
    }

    /**
     * 判断是否有重复的卡号
     * @param cardPre 卡前缀
     * @param startNo 起始编号
     * @param count 制卡数量
     * @param exclude 去除尾数
     * @return
     */
    @GetMapping("/verifyRepeat")
    public Object verifyRepeat(String cardPre,String startNo,Integer count,String exclude){
        boolean boo = memberCardService.verifyRepeat(cardPre,startNo,count,exclude,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("初始化成功", boo);
    }


    /**
     * 配送初始化
     * @param id 批量制卡记录id
     * @return
     */
    @GetMapping("/delivery")
    public Object delivery(Long id){
        QyMap map=QyMap.NEW();
        BatchCardRecord record = batchCardRecordService.findById(id);
        map.setv("record",JSONUtils.include(record,keys));
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        searchable.addSearchParam("memberCardTypeId_eq",record.getCardType().getId());
        List<MemberCardTypeBranch> branchList = memberCardTypeBranchService.findWithSort(searchable);
        if (CollectionUtils.isNotEmpty(branchList)){
            List<Long> bids = branchList.stream().map(MemberCardTypeBranch::getBranchId).collect(Collectors.toList());
            searchable = SearchableUtils.newSearchableWithMerchantFilter();
            searchable.addSearchParam("id_in",bids);
            List<Branch> branches = branchService.findWithSort(searchable);
            map.setv("branches",JSONUtils.include(branches,"id","name"));
            //使用门店
            map.setv("districts",districtService.getBuildTree(CurrentAccountUtils.getAuthenticatedMerchantGroupID(),true,bids,true));
        }
        return ok("初始化成功", map);
    }

    /**
     * 根据门店获取门店可用空卡数量
     * @param branchId 门店id
     * @return
     */
    @GetMapping("/getUsableCard")
    public Object getUsableCard(Long branchId){
        QyMap map=QyMap.NEW();
        Long count = batchCardRecordService.getUsableCard(branchId,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        map.setv("count",count);//空卡数量
        map.setv("useCount", CompuUtils.subtract(5000,count));//可下发数量
        return ok("初始化成功", map);
    }

    /**
     * 计算待下发的卡号范围
     * @param batchId 制卡记录id
     * @param count 制卡数量
     * @return
     */
    @GetMapping("/getNoRange")
    public Object getNoRange(Long batchId,Integer count){
        QyMap map=QyMap.NEW();
        map = batchCardRecordService.getNoRange(batchId,count,CurrentAccountUtils.getAuthenticatedMerchantGroupID());
        return ok("初始化成功", map);
    }



    @ModelAttribute
    public void preparedData(@PathVariable(value="id",required = false) String id,Model model){
        if(StringUtils.isNotBlank(id)){ //如果路径中有id参数则查询实体对象
            BatchCardRecord batchCardRecord = batchCardRecordService.findById(Long.valueOf(id));
            model.addAttribute(batchCardRecord);
        }
    }

    /**
     * 初始化表单数据
     * @param qyMap
     */
    private void initFormDate(QyMap qyMap){
        //会员卡类型
        Searchable searchable = SearchableUtils.newSearchableWithMerchantFilter();
        List<MemberCardType> typeList = memberCardTypeService.findWithSort(searchable);
        qyMap.setv("typeList",JSONUtils.include(typeList,"id","name"));
        //有效期
        qyMap.setv("periodTypes", PeriodType.values());
        qyMap.setv("makeCardTypes", MemberMakeCardType.values());
    }

}